package com.google.code.pathlet.eshop.party.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.code.pathlet.config.anno.SpaceIn;
import com.google.code.pathlet.config.anno.InstanceIn;
import com.google.code.pathlet.core.InstanceSpace;
import com.google.code.pathlet.eshop.party.service.UserService;
import com.google.code.pathlet.eshop.share.vo.UserToken;
import com.google.code.pathlet.web.widget.ResponseLevel;
import com.google.code.pathlet.web.widget.ResponseMessage;

public class AuthenticationAction {
	
	@InstanceIn(path="UserService.pb")
	private UserService userService;
	
	@InstanceIn(path="/request")
	private HttpServletRequest request;
	
	private String username;

	private String password;
	
	private String randKey;

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRandKey() {
		return randKey;
	}
	public void setRandKey(String randKey) {
		this.randKey = randKey;
	}
	
	/**
	 * Get login user instance in current session.
	 * @return
	 * @throws Exception
	 */
	public UserToken getLoginUser() throws Exception {
		return (UserToken)getHttpSession().getAttribute(UserToken.USER_SESSION_KEY);
	}
	
	public ResponseMessage logout() throws Exception {
		getHttpSession().removeAttribute(UserToken.USER_SESSION_KEY);
		return new ResponseMessage(ResponseLevel.INFO, "");
	}
	
	public ResponseMessage login() throws Exception {
		UserToken loginUser = (UserToken)userService.getUser(username, password);
		if (loginUser != null) {
			getHttpSession().setAttribute(UserToken.USER_SESSION_KEY, loginUser);
			return new ResponseMessage(ResponseLevel.INFO, "Login completed！");
		} else {
			return new ResponseMessage(ResponseLevel.ERROR, "Login failed, error username or password！");
		}
	}
	
	private HttpSession getHttpSession() {
		return request.getSession();
	}

}